/**
 * WordSplitter is used to split a string into word segments.
 * First it will read in all valid words from a dictionary, 
 * then find all words from a string.
 */
package parser;

import java.util.*;
import java.io.*;

/**
 * @author robin
 *
 */
public class WordSplitter {
	
	public static int MIN_WORD_LEN = 2;
	private Set<String> wordSet;
	
	public WordSplitter(String filename) throws IOException {
		this.wordSet = new HashSet<String>();
		
		BufferedReader br = new BufferedReader(new FileReader(filename));
		String line;
		while((line = br.readLine()) != null) {
			if(line.length() < MIN_WORD_LEN)
				continue;
			this.wordSet.add(line.toLowerCase());
		}
		
		// add single character word
		this.wordSet.add("a");
		this.wordSet.add("i");
	}
	
	/**
	 * Split the string into available words, as range list.
	 * @param s The string to be splitted.
	 * @return Splitted range list.
	 */
	public List<Range> splitString(String s) {
		s = s.toLowerCase();
		List<Range> rangeList = new ArrayList<Range>();
		int len = s.length();
		
		for(int i = 0; i <= len-1; i++) {
			for(int j = i+1; j <= len; j++) {
				String sub = s.substring(i, j);
				if(this.wordSet.contains(sub)) {
					rangeList.add(new Range(i, j-1));
				}
			}
		}
		return rangeList;
	}
}
